;


cmedit.TargetManager = (function($, window, document) {
    var thisContext;
    var index = 0;
    var startPage = 1;
    var userColumnIds = [];
    var selectIds = [];
    var selectColumnIds = [];
    var listTotalCount;
    var listPageSize;
    var loadTimeout = cmedit.global.loadTimeout;
    var creImportTaskFlag = window.sessionStorage.getItem(cmedit.global.creImportTaskFlag);
    var userColumnIds = window.sessionStorage.getItem(cmedit.global.userColumnIds);
    var bigColumnId = window.sessionStorage.getItem(cmedit.global.bigColumnId);
    var columnInfo = JSON.parse(window.parent.sessionStorage.getItem(cmedit.global.columnInfo));
    var allColumnInfo = JSON.parse(window.parent.sessionStorage.getItem(cmedit.global.allColumnInfo));
    var privilegeIds = window.sessionStorage.getItem(cmedit.global.privilegeIds);
    var tenantId = window.localStorage.getItem("tenantId");
    var userId = window.sessionStorage.getItem("userId");
    var token = window.sessionStorage.getItem("token");
    var distributeFlag = window.sessionStorage.getItem("distributeFlag");
    var distributeSecretFlag = window.parent.sessionStorage.getItem("distributeSecretFlag");
    var topUtil; //顶层工具类
    var singleMainGuid;
    var orderName = '';
    var pageNow;
    var orderDirection = '';
    var TargetManagerClass = function() {

    }
    TargetManagerClass.prototype = {
        constructor: TargetManagerClass,

        init: function() {
            thisContext = this;
            topUtil = window.parent.cmedit.global;
            thisContext.initViewStyle();
            thisContext.initColumn();
            thisContext.initData();
            //        	thisContext.initPage();
            thisContext.initEvent();
            //        	thisContext.initTargetList();
        },
        refresh: function() {
            $('#manusendtaskTable').bootstrapTable('refresh');
        },
        /**
         * 初始化页面视图
         */
        initViewStyle: function() {
            // 如果用户没有签发权限，禁用签发任务页
            if (privilegeIds.indexOf(cmedit.global.privilegeDistribute) == -1 || distributeSecretFlag == '1') {
                $("#distributeButton").css('display', 'none');
                $("#distributeButton2").css('display', 'none');
            } else {
                if (distributeFlag == 1) {
                    $("#distributeButton").css('display', 'inline-block');
                } else if (distributeFlag == 2) {
                    $("#distributeButton2").css('display', 'inline-block');
                } else if (distributeFlag == 3) {
                    $("#distributeButton3").css('display', 'inline-block');
                }
            }
            // 如果用户没有下载权限，禁用下载按钮
            if (privilegeIds.indexOf(cmedit.global.privilegeExportword) == -1) {
                $("#downloadButton").hide();
            }
            // 如果用户没有删除全部权限，禁用删除按钮
            if (privilegeIds.indexOf(cmedit.global.privilegeDelFinishscripts) != -1 || 
            		privilegeIds.indexOf(cmedit.global.privilegeDelallscripts) != -1) {
                $("#deleteButton").show();
            }
            // 如果用户没有签发撤回权限，禁用撤回按钮
            if (privilegeIds.indexOf(cmedit.global.privilegeDistributeRevoke) == -1) {
            	$("#revokeButton").hide();
            }


            $('.re_contleft .slimScrollDiv').css('height', $(document).height() - 116 + 'px');
            $('.tab-content').css('height', $('.portlet-body').innerHeight() + 'px');
            //            $('.line-body').css('height',$('.cont_container').innerHeight()-203+'px');
            //
            //            /*修改滚动条样式*/
            //            var linescroll_height=$('.line-body').height();
            //            thisContext.scrollType('line-body',linescroll_height);

            $('#startTime').datepicker({ clearBtn: true, format: 'yyyy-mm-dd', autoclose: true });
            $('#endTime').datepicker({ clearBtn: true, format: 'yyyy-mm-dd', autoclose: true });
        },
        /**
         * 时间排序
         */
        orderby: function(id, orderDirectionName) {
            orderName = id;
            orderDirection = orderDirectionName;
            thisContext.initData(pageNow);
        },
        recordBox: function(obj, mainGuid) {
            window.parent.cmedit.ManuscriptSystem.recordBox(obj, mainGuid);
        },
        /**
         *预览窗口
         */
        enterPreview: function(obj, mainGuid) {
            window.parent.cmedit.ManuscriptSystem.enterPreview(obj, mainGuid);
        },
        popoverBox: function(obj, mainGuid) {
            window.parent.cmedit.ManuscriptSystem.popoverBox(obj, mainGuid);
        },
        /**
         * 初始化数据
         */
        initData: function(_currentPage,_pageSize) {
            window.parent.cmedit.ManuscriptSystem.updatePortalStorageExpireTime();
            var finalOptionList = window.parent.cmedit.ManuscriptSystem.finalOptionList;
            for (var i = 0; i < finalOptionList.length; i++) {
                window.sessionStorage.removeItem("FINALOPTION_" + finalOptionList[i]);
            }
            window.parent.cmedit.ManuscriptSystem.finalOptionList = [];

            //        	var templateHeaderData = {
            //        			creImportTaskFlag : creImportTaskFlag,
            //				}
            //        	var htmlHeader = template('manusendListHeader', templateHeaderData);
            //        	$("#manusendBodyHeader").html(htmlHeader);
            var $tableid = $('#manusendtaskTable');
            var url = cmedit.global.cmsPath + "CreImportController/getCreImportTaskByPage";
            var gc = JSON.parse(window.sessionStorage.getItem(cmedit.global.cmeditSendTask));
            var cmeditList = JSON.parse(window.sessionStorage.getItem(cmedit.global.cmeditTypes));
            var hasCheckbox = true;
            selectIds = [];
            selectColumnIds = [];
            //            $('#allSelected').prop('checked',false);
            //        	$('#manusendBody').html(cmedit.global.loaderHtml);
            if ($('#searchContent').val() != null && $('#searchContent').val() != '') {
                var title = $('#searchContent').val();
            } else {
                var title = '';
            }
            //          if($('#endTime').val()!=null && $('#endTime').val()!=''){
            if (($('#endTime').val() != null && $('#endTime').val() != '') || ($('#startTime').val() != null && $('#startTime').val() != '')) {
                var dateranges = $("#startTime").val() + " - " + $("#endTime").val();
            } else {
                var dateranges = '';
            }
            var currentPage = _currentPage ? _currentPage : 1;
            var pageSize =_pageSize ? _pageSize : 10;
            var states = $(".container_buttons button[class*='active']").attr("states");
            var columnId = $("#preReportColumn").val() != "" ? $("#preReportColumn").val() : "";
            //var manuscriptTargetGuid = $("#preReportColumn").val();
            var queryParams = {
                mainHeader: title,
                dateranges: dateranges,
                columnId: columnId,
                mainType: 0, //CMS稿件
                //manuscriptTargetGuid:manuscriptTargetGuid.replace("_CRE",""),
                userColumnIds: userColumnIds,
                currentPage:currentPage,
                pageSize:pageSize
            };
            var tableParams = {
                $tableid: $tableid,
                url: url,
                gc: gc,
                hasCheckbox: hasCheckbox,
                tenantId: tenantId,
                userId: userId,
                token: token,
                cmeditList: cmeditList,
                creImportTaskFlag: creImportTaskFlag,
                resourceType: "manuSendTask",
                callBackRender: function() {
                    // 如果用户没有编辑权限，禁用复制操作按钮
                    if (privilegeIds.indexOf(cmedit.global.privilegeWritescripts) == -1) {
                        $(".operateCopyItem").css('display', 'none');
                        $(".lineTip1").css('display', 'none');
                    }
                    //如果没有删除全部权限，那就连删除一切干掉
                    if (privilegeIds.indexOf(cmedit.global.privilegeDelFinishscripts) == -1 && 
                    		privilegeIds.indexOf(cmedit.global.privilegeDelallscripts) == -1) {
                        $(".operateDeleteBtn").css('display', 'none');
                        $(".lineTip2").css('display', 'none');
                    }
                    if (privilegeIds.indexOf(cmedit.global.privilegeWritescripts) == -1 &&
                        privilegeIds.indexOf(cmedit.global.privilegeDelFinishscripts) == -1 && 
                        privilegeIds.indexOf(cmedit.global.privilegeDelallscripts) == -1) {
                        $("#operateButton").css('display', 'none');
                    }
                    if (creImportTaskFlag != 0) {
                        $(".retryI").on('click', function(e) {
                            $(".dropReason").hide();
                            var a = this;
                            thisContext.statusMouseover(this);

                            $(document).on('click', function() {
                                thisContext.statusMouseout(a);
                            });

                            e.stopPropagation();
                        });
                    }
                },
                callBackLoadData:function(start,size){
                	thisContext.initData(start,size);
                }
            };
            console.log('tableParams:' + tableParams);
            TableInit(tableParams, queryParams);
        },
        /**
         * 初始化分页
         */
        initPage: function(totalPage) {
            $("#pagination").whjPaging({
                /*pageSizeOpt: [
                    {'value': 5, 'text': '5/page', 'selected': true},
                    {'value': 10, 'text': '10/page'},
                    {'value': 15, 'text': '15/page'},
                    {'value': 20, 'text': '20/page'}
                ],*/
                totalPage: totalPage,
                showPageNum: 4,
                firstPage: '<i class="iconfont icon-diyiye"></i>',
                previousPage: '<i class="iconfont icon-shangyiye"></i>',
                nextPage: '<i class="iconfont icon-xiayiye"></i>',
                lastPage: '<i class="iconfont icon-weiye"></i>',
                skip: 'skip',
                confirm: 'go',
                refresh: 'refresh',
                totalPageText: 'the total {} pages',
                isShowFL: true,
                isShowPageSizeOpt: false,
                isShowSkip: false,
                isShowRefresh: false,
                isShowTotalPage: false,
                isResetPage: true,
                callBack: function(currPage, pageSize) {
                    pageNow = currPage;
                    thisContext.initData(currPage);
                }
            });
            /*$('#pagination').whjPaging('setPage',1,totalPage);*/
        },
        /**
         * 初始化事件
         */
        initEvent: function() {
            $('.nav-link').on('click', function() {
                $('.nav-link').removeClass('nav_active');
                $(this).addClass('nav_active');
            });
            $('.container_buttons button').on('click', function() {
                $(this).addClass('active').siblings().removeClass('active');
                thisContext.initData();
            });


            /*//栏目筛选功能
			$('#preReportColumn').change(function(){
				thisContext.initData();
			});*/
            //时间筛选绑定change事件
            //			$('#endTime').change(function() {
            //				thisContext.initData();
            //			});
            //刷新列表
            $('.send_refresh').on('click', function() {
                $("#preReportColumn").val('');
                $('#searchContent').val('');
                $("#preReportColumn").selectpicker('refresh');
                $(".container_buttons button[states='']").addClass('active').siblings().removeClass('active');
                $('.date-picker input').val('').datepicker('clearDates');
                //thisContext.initData();
            });

            $('.iStatus').on('mouseover', function() {
                debugger;
                var tipHeight = $(window).height() - $(this).offset().top;
                console.log(tipHeight);
                if (tipHeight < 122) {
                    $(this).next().removeClass('dropdown_tiptop');
                    $(this).next().addClass('dropdown_tipbot');
                }
                /*manuscriptSystem.isHeight();*/
                $(this).next().show();
            });
            $('.iStatus').on('mouseout', function() {
                $(this).next().hide();
            });
        },
        /**
         * 详情页
         */
        entersendDetail: function(mainGuid, mainHeader) {
            if (mainHeader == "manuscript") {
                mainHeader = $("#" + mainGuid).attr("mainheader");
            }
            window.parent.cmedit.ManuscriptSystem.enterDetail(mainGuid, mainHeader, "sendTask");
        },
        /**
         *滚动条样式
         */
        scrollType: function(scrollId, scrollHeight) {
            $('.' + scrollId).slimScroll({
                height: scrollHeight, //可滚动区域高度
                size: '5px', //组件宽度
                color: '#999', //滚动条颜色
                railOpacity: .3, //滚动条透明度
                disableFadeOut: true, //鼠标经过可滚动区域时显示组件，离开时隐藏组件
                wheelStep: 20, //滚轮滚动量
                alwaysVisible: true, //始终显示组件
                borderRadius: '7px' //滚动条圆角
            });
        },
        /**
         * 全选
         */
        allfileSelected: function() {
            if ($('#allSelected').prop('checked')) {
                $('.select-check').prop('checked', true);
                $('.list_check').addClass('list_checked');
                $('.res-one').addClass('ulChecked');
                selectIds = [];
                selectColumnIds = [];
                for (var i = 0; i < $('#manusendBody .list_checked').length; i++) {
                    selectIds.push($('#manusendBody .listone_check').eq(i).attr('id'));
                    selectColumnIds.push($('#manusendBody .listone_check').eq(i).attr('columnId'));
                }
            } else {
                $('.select-check').prop('checked', false);
                $('.list_check').removeClass('list_checked');
                $('.res-one').removeClass('ulChecked');
                selectIds = [];
                selectColumnIds = [];
            }
        },
        /**
         * 选择框点击事件
         */
        listOneCheckClick: function(obj, id, columnId) {
            if (!$(obj).prev().prop('checked')) {
                $(obj).addClass('list_checked');
                selectIds.push(id);
                selectColumnIds.push(columnId);
                if (listTotalCount >= listPageSize) {
                    if ($('.list_checked').length >= listPageSize) {
                        $('#allSelected').prop('checked', true);
                    }
                } else {
                    if ($('#manusendBody .list_checked').length == listTotalCount) {
                        $('#allSelected').prop('checked', true);
                    }
                }
            } else {
                $(obj).removeClass('list_checked');
                selectIds.splice($.inArray(id, selectIds), 1);
                selectColumnIds.splice($.inArray(id, selectColumnIds), 1);
                $('#allSelected').prop('checked', false);
                $('#allSelected').next().removeClass('list_checked');
            }
        },
        /**
         *  初始化栏目
         */
        /*  initColumn: function() {
              var postData = {
                  "key": "0003",
              }
              topUtil.ajaxRequest({
                  type: "post",
                  async: false,
                  dataType: "json",
                  url: cmedit.global.cmsPath + "UserInfoController/getUserColumnByUserId",
                  data: postData,
                  success: function(data) {
                      if (data.status) {
                          for (var i = 0; i < data.data.length; i++) {
                              userColumnIds.push(data.data[i].id);
                              $("#preReportColumn").append('<option value="' + data.data[i].id + '">' + data.data[i].name + '</option>');
                          }
                          userColumnIds = JSON.stringify(userColumnIds);
                          $("#preReportColumn").selectpicker('refresh');
                      } else {
                          $.notify(data.msg);
                      }
                  }
              });
          },*/
        /**
         * 初始化栏目
         */
        initColumn: function() {
            //判断该成员是否属于大采访部，如果是，则可以显示所有的栏目
            if (userColumnIds.indexOf(bigColumnId) > 0) {
                for (var i = 0; i < allColumnInfo.length; i++) {
                    $("#preReportColumn").append('<option value="' + allColumnInfo[i].id + '">' + allColumnInfo[i].name + '</option>');
                }
            } else {
                for (var i = 0; i < columnInfo.length; i++) {
                    $("#preReportColumn").append('<option value="' + columnInfo[i].id + '">' + columnInfo[i].name + '</option>');
                }
            }
            $("#preReportColumn").selectpicker('refresh');
        },
        /**
         * 初始化签发目标列表
         */
        initTargetList: function() {
            topUtil.ajaxRequest({
                type: "post",
                async: false,
                dataType: "json",
                url: cmedit.global.cmsPath + "CmsController/getCmsTargetSystem",
                success: function(data) {
                    if (data.status) {
                        var html = '';
                        var list = data.data;
                        for (var i = 0; i < list.length; i++) {
                            $("#preReportColumn").append('<option value="' + list[i].creTargetGuid + '">' + list[i].creTargetName + '</option>');
                        }
                        $("#preReportColumn").selectpicker('refresh');
                    } else {
                        $.notify(data.msg);
                    }
                }
            });
        },

        /**
         * 签发重试
         * @param mntGuid
         * @param mainGuid
         */
        reTargetDistribute: function(mainGuid) {
            var postData = {
                "mainGuid": mainGuid,
            }
            topUtil.ajaxRequest({
                type: "post",
                async: true,
                dataType: "json",
                url: cmedit.global.cmsPath + "CmsNewTargetController/reTargetDistributionAll",
                data: postData,
                success: function(data) {
                    if (data.status) {
                        thisContext.initData();
                        $.notify("签发重试成功");
                    } else {
                        $.notify(data.msg);
                    }
                }
            });
        },

        /**
         * 入库重试
         * @param misGuid
         */
        retryImport: function(misGuid) {
            var misGuids = [];
            misGuids.push(misGuid);

            var postData = {
                misGuids: JSON.stringify(misGuids)
            }
            topUtil.ajaxRequest({
                type: "post",
                async: true,
                dataType: "json",
                url: cmedit.global.cmsPath + "CreImportController/retryImportTask",
                data: postData,
                success: function(data) {
                    if (data.status) {
                        $.notify("入库重试成功");
                        thisContext.initData();
                    } else {
                        $.notify(data.msg);
                    }
                }
            });
        },

        /**
         * 添加入库任务
         * @param mainGuid
         */
        addImportTask: function(mainGuid) {
            var mainGuids = [];
            mainGuids.push(mainGuid);
            var postData = {
                mainGuids: JSON.stringify(mainGuids)
            }
            topUtil.ajaxRequest({
                type: "post",
                async: true,
                dataType: "json",
                url: cmedit.global.cmsPath + "CreImportController/addImportTask",
                data: postData,
                success: function(data) {
                    if (data.status) {
                        $.notify("添加入库任务成功");
                        thisContext.initData();
                    } else {
                        $.notify(data.msg);
                    }
                }
            });
        },

        /**
         * 删除签发记录
         * @param mntGuid
         */
        deleteDistribute: function(mntGuid) {
            window.parent.cmedit.ManuscriptSystem.deleteDistribute(mntGuid);
        },

        /**
         * 状态提示
         */
        statusMouseover: function(e) {
            var tipHeight = $(window).height() - $(e).offset().top;
            var dropHeight = $(e).next().height() + 32;
            var offSetHeight = dropHeight - 12;
            if (tipHeight < (dropHeight + 40)) {
                $(e).next().removeClass('dropdown_tiptop');
                $(e).next().addClass('dropdown_tipbot');
                $('head').append("<style>.dropdown_tipbot:before{ top:" + offSetHeight + "px}</style>");
                $('head').append("<style>.dropdown_tipbot:after{ top:" + offSetHeight + "px}</style>");
            }
            $(e).next().show();
            $('.dropdown_tipbot').css('top', '-' + dropHeight + 'px');
        },
        statusMouseout: function(e) {
            $(e).next().hide();
        },

        /**
         * 点击确定签发更改签发记录
         */
        determineTarget: function(obj) {
            window.parent.cmedit.ManuscriptSystem.determineTarget(obj);
        },

        /**
         * 点击分发
         */
        sendTaskForm: function(mainGuid, columnId) {
            var choosenList = $('#manusendtaskTable').bootstrapTable('getSelections');
            if (choosenList.length > 0 || topUtil.isNotEmpty(mainGuid)) {
                var columnIds = [];
                var mainGuids = [];
                //判断是单条记录选择的还是勾选的
                if (topUtil.isNotEmpty(mainGuid)) {
                    singleMainGuid = mainGuid;
                    mainGuids.push(mainGuid);
                    columnIds.push(columnId);
                } else {
                    //如果入库开关开启了，那么进行签发的时候要判断，如果选中的稿件中有未入库成功的，则不能进行签发
                    /*if (creImportTaskFlag == 1) {
                        var misStatus;
                        for (var i = 0; i < choosenList.length; i++) {
                            misStatus = choosenList[i].manuscriptImportTask.misStatus;
                            if (misStatus != 5) {
                                $.notify("选中的稿件有未入库成功的，不能进行签发");
                                return;
                            }
                        }
                    }*/
                    for (var i = 0; i < choosenList.length; i++) {
                        columnIds.push(choosenList[i].mainColumnId);
                        mainGuids.push(choosenList[i].mainGuid);
                    }
                }
                var postData = {
                        columnIds: JSON.stringify(columnIds),
                        mainGuids: JSON.stringify(mainGuids),
                    }
                    //获取公共的签发目标
                topUtil.ajaxRequest({
                    type: "post",
                    async: true,
                    dataType: "json",
                    url: cmedit.global.cmsPath + "CmsNewTargetController/bulkIssueTarget",
                    data: postData,
                    success: function(data) {
                        if (data.status) {
                            //    						var url="http://10.10.1.32:8080/distributemanager/application/initDistributePage";
                            var url = data.data.targetUrl;
                            var arg = data.data;
                            window.parent.cmedit.ManuscriptSystem.formSubmit(url, arg);
                        } else {
                            $.notify(data.msg);
                        }
                    }
                });
            } else {
                $.notify("请选择一条稿件进行签发");
            }
        },

        /**
         * 签发弹框
         */
        sendTaskModal: function(mainGuid, columnId) {
            var choosenList = $('#manusendtaskTable').bootstrapTable('getSelections');
            if (choosenList.length > 0 || topUtil.isNotEmpty(mainGuid)) {
                var columnIds = [];
                var mainGuids = [];
                //判断是单条记录选择的还是勾选的
                if (topUtil.isNotEmpty(mainGuid)) {
                    singleMainGuid = mainGuid;
                    mainGuids.push(mainGuid);
                    columnIds.push(columnId);
                } else {
                    //如果入库开关开启了，那么进行签发的时候要判断，如果选中的稿件中有未入库成功的，则不能进行签发
                    /*if (creImportTaskFlag == 1) {
                        var misStatus;
                        for (var i = 0; i < choosenList.length; i++) {
                            misStatus = choosenList[i].manuscriptImportTask.misStatus;
                            if (misStatus != 5) {
                                $.notify("选中的稿件有未入库成功的，不能进行签发");
                                return;
                            }
                        }
                    }*/
                    for (var i = 0; i < choosenList.length; i++) {
                        columnIds.push(choosenList[i].mainColumnId);
                        mainGuids.push(choosenList[i].mainGuid);
                    }
                }
                var postData = {
                        columnIds: JSON.stringify(columnIds),
                        mainGuids: JSON.stringify(mainGuids),
                    }
                    //获取公共的签发目标
                topUtil.ajaxRequest({
                    type: "post",
                    async: true,
                    dataType: "json",
                    url: cmedit.global.cmsPath + "CmsController/getCmsTargetSystemArr",
                    data: postData,
                    success: function(data) {
                        if (data.status) {
                            var html = '';
                            var creTargetList = data.data.creTargetList;
                            var cmsTargetList = data.data.cmsTargetList;
                            if (creTargetList.length > 0 || cmsTargetList.length > 0) {
                                for (var i = 0; i < creTargetList.length; i++) {
                                    html += '<label class="mt-checkbox mt-checkbox-outline">' +
                                        '<input type="checkbox" name="targetCheck" id="' + creTargetList[i].creTargetGuid + '"> ' + creTargetList[i].creTargetName + '' +
                                        '<span></span>' +
                                        '</label><br/>';
                                }
                                for (var i = 0; i < cmsTargetList.length; i++) {
                                    html += '<label class="mt-checkbox mt-checkbox-outline">' +
                                        '<input type="checkbox" name="targetCheck" id="' + cmsTargetList[i].cmsTargetGuid + '"> ' + cmsTargetList[i].cmsTargetName + '' +
                                        '<span></span>' +
                                        '</label><br/>';
                                }

                                $("#targetListArr", parent.document).html(html);
                                $("input[name='targetCheck']", parent.document).on('change', function() {
                                    var i = $("input[name='targetCheck']:checked", parent.document).length;
                                    if (i > 0) {
                                        $("#confirmDistribute", parent.document).attr("disabled", false);
                                    } else {
                                        $("#confirmDistribute", parent.document).attr("disabled", true);
                                    }
                                });
                                $("#confirmDistribute", parent.document).attr("disabled", true);
                                window.parent.cmedit.ManuscriptSystem.sendTaskModalShow('iframe_manuSendTask');
                            } else {
                                $("#targetListArr", parent.document).html("无签发目标");
                                $("#confirmDistribute", parent.document).attr("disabled", true);
                                $.notify("无签发目标！");
                            }

                        } else {
                            $.notify(data.msg);
                        }
                    }
                });
            } else {
                $.notify("请选择一条稿件进行签发");
            }
        },
        /**
         * ----------------------------签发弹框新增3--------------------------
         */
        sendTaskModal3: function(mainGuid, columnId) {
            // 清空modal数据
            $("#sentTaskTreeContainer #book", parent.document).html("");
            $("#sentTaskTreeContainer #keyword", parent.document).val("");
            var choosenList = $('#manusendtaskTable').bootstrapTable('getSelections');
            console.log(choosenList);
            if (choosenList.length > 0 || topUtil.isNotEmpty(mainGuid)) {
                if (window.parent.cmedit.ManuscriptSystem.getAsyncCreTarget()) {
                    $.notify("请先同步签发目标");
                    return;
                }
                $("#confirmDistributeButton", parent.document).attr("disabled", true);
                window.parent.cmedit.ManuscriptSystem.sendTaskModal3Show('iframe_manuSendTask');
                $('#selectedSendTargetUl',parent.document).find('li').removeClass("selectedbackground");
                $(".censorSendTaskModal3",parent.document).hide();
            	$("#confirmDistributeButton",parent.document).attr("onclick",'cmedit.ManuscriptSystem.confirmDistributeButton()');
                var columnIds = [];
                var mainGuids = [];
                var targetArr;
                //判断是单条记录选择的还是勾选的
                if (topUtil.isNotEmpty(mainGuid)) {
                    singleMainGuid = mainGuid;
                    mainGuids.push(mainGuid);
                    columnIds.push(columnId);
                } else {
                    for (var i = 0; i < choosenList.length; i++) {
                        columnIds.push(choosenList[i].mainColumnId);
                        mainGuids.push(choosenList[i].mainGuid);
                    }
                }
                var postData = {
                        columnIds: JSON.stringify(columnIds),
                        mainGuids: JSON.stringify(mainGuids),
                    }
                    //获取公共的签发目标
                topUtil.ajaxRequest({
                    type: "post",
                    async: false,
                    dataType: "json",
                    url: cmedit.global.cmsPath + "CmsController/getCmsTargetSystemArr",
                    data: postData,
                    success: function(data) {
                        if (data.status) {
                            targetArr = data.data.creTargetList;
                        }
                    }
                });
                console.log("公共的签发目标", targetArr);

                // 选中的稿件列表
                var selectedItems = "";
                choosenList.forEach(function(v, k, arra) {
                    selectedItems += ' <li class="selectedLi" mainGuid="' + v.mainGuid + '">' + v.mainHeader + '</li>';
                })
                $("#selectedUl", parent.document).html(selectedItems);
                // 选中的稿件列表


                $.ajax({
                    type: "get",
                    async: true,
                    dataType: "json",
                    url: cmedit.global.cmsPath + 'CreDistributeController/getChannels',
                    data: {
                        channelType: "1,2"
                    },
                    beforeSend: function(XHR) {
                        //                        XHR.setRequestHeader("tenantId", '0006992C-0909-4029-A18C-A1FC329CA2E3');
                        XHR.setRequestHeader("tenantId", tenantId);
                        XHR.setRequestHeader("token", token);
                    },
                    success: function(data) {
                        if (data.status) {
                            // 签发渠道目标
                            var selectedItems = "";
                            var channelList = data.data.channelList;
                            var channelArry = [];
                            channelList.forEach(function(channel) {
                                targetArr.forEach(function(target) {
                                    var channelId = target.creServiceName.replace("CMS_", "");
                                    if (channel.channelId == channelId) {
                                        channelArry.push(channel);
                                    }
                                });
                            })
                            console.log("实际签发目标", channelArry);

                            channelArry.forEach(function(v, k, arra) {
                            selectedItems += '<li onclick="cmedit.ManuscriptSystem.showTargetColumnCategory(\'NewsEditingSuite-platform-column-' + v.channelId + '\')"><label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">';
                                selectedItems += '<input channelId="' + v.channelId + '" channelName="' + v.channelName + '" channelType="' + v.channelType + '" distrColumn="" name="issuedTarget" type="checkbox">';
                            selectedItems +=  ' <span></span></label><span>'+v.channelName+'</span></li>'
                                if (topUtil.isNotEmpty(v.columnList)) window.sessionStorage.setItem("NewsEditingSuite-platform-column-" + v.channelId, JSON.stringify(v.columnList));
                            if(topUtil.isNotEmpty(v.categoryList))window.sessionStorage.setItem("NewsEditingSuite-platform-category-" + v.channelId,JSON.stringify(v.categoryList));    
                            if(topUtil.isNotEmpty(v.moulds))window.sessionStorage.setItem("NewsEditingSuite-platform-moulds-" + v.channelId,JSON.stringify(v.moulds));
                                // <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
                            })
                            $("#selectedSendTargetUl", parent.document).html(selectedItems);
                            if (channelArry.length > 0) {
                                $('#selectedSendTargetUl',parent.document).find('li').on('click',function(){
                                    $('#selectedSendTargetUl',parent.document).find('li').removeClass("selectedbackground");
                                    $(this).addClass("selectedbackground");
                                });
                                $("input[name='issuedTarget']", parent.document).on('change', function () {
                                    //判断是否勾选来展示栏目信息
                                    if($(this).prop("checked")){
                                        var channelid = $(this).attr("channelid");
                                        window.parent.cmedit.ManuscriptSystem.showTargetColumnCategory(channelid);
                                        window.parent.cmedit.ManuscriptSystem.showTargetDemo('NewsEditingSuite-platform-moulds-' + channelid);
                                        $("#channelId_hidden",parent.document).val(channelid);
                                    }else{
                                    	window.parent.cmedit.ManuscriptSystem.showTargetColumnCategory("");
                                        window.parent.cmedit.ManuscriptSystem.showTargetDemo('NewsEditingSuite-platform-moulds-');
                                        $("#channelId_hidden",parent.document).val("");
                                    };

                                    var i = $("input[name='issuedTarget']:checked", parent.document).length;
                                    if (i > 0) {
                                        $("#confirmDistributeButton", parent.document).attr("disabled", false);
                                    } else {
                                        $("#confirmDistributeButton", parent.document).attr("disabled", true);
                                    }
                                });
                               /* $("input[name='issuedTarget']", parent.document).on('change', function () {
                                    //判断是否勾选来展示栏目信息
                                    if($(this).prop("checked")){
                                        var channelid = $(this).attr("channelid");
                                        window.parent.cmedit.ManuscriptSystem.showTargetColumns('NewsEditingSuite-platform-column-' + channelid);
                                        window.parent.cmedit.ManuscriptSystem.showTargetDemo('NewsEditingSuite-platform-moulds-' + channelid);
                                    }else{
                                        window.parent.cmedit.ManuscriptSystem.showTargetColumns('NewsEditingSuite-platform-column-');
                                        window.parent.cmedit.ManuscriptSystem.showTargetDemo('NewsEditingSuite-platform-moulds-');

                                    };
                                $("input[name='issuedTarget']", parent.document).on('change', function() {
                                    var i = $("input[name='issuedTarget']:checked", parent.document).length;
                                    if (i > 0) {
                                        $("#confirmDistributeButton", parent.document).attr("disabled", false);
                                    } else {
                                        $("#confirmDistributeButton", parent.document).attr("disabled", true);
                                    }
                                });*/
                            }
                            // 签发目标
                        } else {
                            $.notify(data.msg);
                        }
                    }
                });
                return;
                var columnIds = [];
                var mainGuids = [];
                //判断是单条记录选择的还是勾选的
                if (topUtil.isNotEmpty(mainGuid)) {
                    singleMainGuid = mainGuid;
                    mainGuids.push(mainGuid);
                    columnIds.push(columnId);
                } else {
                    for (var i = 0; i < choosenList.length; i++) {
                        columnIds.push(choosenList[i].mainColumnId);
                        mainGuids.push(choosenList[i].mainGuid);
                    }
                }
                var postData = {
                        columnIds: JSON.stringify(columnIds),
                        mainGuids: JSON.stringify(mainGuids),
                    }
                    //获取公共的签发目标
                topUtil.ajaxRequest({
                    type: "post",
                    async: true,
                    dataType: "json",
                    url: cmedit.global.cmsPath + "CmsController/getCmsTargetSystemArr",
                    data: postData,
                    success: function(data) {
                        if (data.status) {
                            var appendHtml = '';
                            var targetList = data.data;
                            if (targetList.length > 0) {
                                for (var i = 0; i < targetList.length; i++) {
                                    appendHtml += '<div class="mt-checkbox-list">' +
                                        '<label class="mt-checkbox mt-checkbox-outline">' +
                                        '<input type="checkbox" name="targetCheck" id="' + targetList[i].creTargetGuid + '">' + targetList[i].creTargetName + '' +
                                        '<span></span>' +
                                        '</label>' +
                                        '</div>';
                                }
                                $("#targetListArr", parent.document).html(appendHtml);
                                $("input[name='targetCheck']", parent.document).on('change', function() {
                                    var i = $("input[name='targetCheck']:checked", parent.document).length;
                                    if (i > 0) {
                                        $("#confirmDistribute", parent.document).attr("disabled", false);
                                    } else {
                                        $("#confirmDistribute", parent.document).attr("disabled", true);
                                    }
                                });
                                $("#confirmDistribute", parent.document).attr("disabled", true);
                                window.parent.cmedit.ManuscriptSystem.sendTaskModalShow('iframe_manuSendTask');
                            } else {
                                $("#targetListArr", parent.document).html("无签发目标");
                                $("#confirmDistribute", parent.document).attr("disabled", true);
                                $.notify("无签发目标！");
                            }
                        } else {
                            $.notify(data.msg);
                        }
                    }
                });
            } else {
                $.notify("请选择一条稿件进行签发");
            }
        },
        /**
         *列表状态显示
         */
        /*istatusMouseover : function(e){
        	var tipHeight=$(window).height()-$(e).offset().top;
            console.log(tipHeight);
            if(tipHeight<122){
                $(e).next().removeClass('dropdown_tiptop');
                $(e).next().addClass('dropdown_tipbot');
            }
            manuscriptSystem.isHeight();
            $(e).next().show();
        },
        istatusMouseout : function(e){
        	$(e).next().hide();
        },*/

        /**
         * 删除记录
         * @param downloadStatusGuid
         */
        delResoure: function (mainGuid,userId,mainStatus) {
        	var selectIds = [];
            var mainObj = {};
            mainObj.mainGuid = mainGuid;
            mainObj.mainCreateUserId = userId;
            mainObj.mainStatus = mainStatus;
            selectIds.push(mainObj);
            window.parent.cmedit.ManuscriptSystem.delResoure(selectIds, "manuSendTask");
        },

        /**
         * 批量删除
         */
        selectDelect: function() {
            var mainGuids = [];
            var choosenList = $('#manusendtaskTable').bootstrapTable('getSelections');
            if (choosenList.length == 0) {
                $.notify("请先选择记录！");
                $('.manuLoader').hide();
                return false;
            } else {
                for (var i = 0; i < choosenList.length; i++) {
                	var mainObj = {};
                	mainObj.mainGuid = choosenList[i].mainGuid;
                	mainObj.mainCreateUserId = choosenList[i].mainCreateUserId;
                	mainObj.mainStatus = choosenList[i].mainStatus;
                	mainGuids.push(mainObj);
                }
                window.parent.cmedit.ManuscriptSystem.delResoure(mainGuids, "manuSendTask");
            }
        },
        /**
         * 新增撤回功能
         * 
         */
        recall: function() {
            var choosenList = $('#manusendtaskTable').bootstrapTable('getSelections');
            if (choosenList.length == 0) {
                $.notify("请先选择撤回条目！");
                $('.manuLoader').hide();
                return false;
            } else if(choosenList.length == 1){
                var mainGuid = choosenList[0].mainGuid
                    topUtil.ajaxRequest({
                type: "post",
                async: true,
                dataType: "json",
                url: cmedit.global.cmsPath + "CmsController/getRevokeChannels?mainGuid="+mainGuid,    
                success: function(data) {
                    if (data.status) {
                        let chooseLists=data.data
                        let sendmanuscriptTargetGuid=[]
                        let myGuid=[]
                        for(var i = 0;i<chooseLists.length;i++){
                           sendmanuscriptTargetGuid.push(chooseLists[i].manuscriptTargetName + "、")
                           var myDate={}
                           myDate.mntGuid=chooseLists[i].mntGuid
                           myGuid.push(myDate)
                        }
                        console.log('检测是否有数据',myGuid)
                          window.parent.cmedit.ManuscriptSystem.recallResoure(mainGuid,sendmanuscriptTargetGuid,myGuid,"manuSend");
                    }else{
                        $.notify('无可撤回签发成功的分发任务');
                    }
                }
            });
            }else{
                $.notify("抱歉,目前只支持单条撤回！");
                $('.manuLoader').hide();
                return false; 
            }
        },
        /**
         *列表状态显示
         */
        istatusMouseover: function(e) {
            var tipHeight = $(window).height() - $(e).offset().top;
            console.log(tipHeight);
            if (tipHeight < 122) {
                $(e).next().removeClass('dropdown_tiptop');
                $(e).next().addClass('dropdown_tipbot');
            }
            /*manuscriptSystem.isHeight();*/
            $(e).next().show();
        },
        istatusMouseout: function(e) {
            $(e).next().hide();
        },
        checkBox: function(obj) {
        	var thisObj = $(obj);
        	var name = thisObj.attr("name");
        	var checked = thisObj.prop("checked");
        	if(name == 'parentCopyMic'){
        		if(checked){
        			thisObj.closest(".showDropDown").find("input[name='childrenCopyMic']").prop("checked",true);
        		}else{
        			thisObj.closest(".showDropDown").find("input[name='childrenCopyMic']").prop("checked",false);
        		}
        	}else if(name == 'childrenCopyMic'){
        		var checkedlength = thisObj.closest(".showDropDown").find("input[name='childrenCopyMic']:checked").length;
        		if(checkedlength ==2){
        			thisObj.closest(".showDropDown").find("input[name='parentCopyMic']").prop("checked",true);
        		}else{
        			thisObj.closest(".showDropDown").find("input[name='parentCopyMic']").prop("checked",false);
        		}
        	}
        },
        /**
         * 复制稿件
         * @param mainGuid
         * @param mainType
         */
        copyManuscript: function(mainGuid, mainType) {
            window.parent.cmedit.ManuscriptSystem.copyManuscript(mainGuid, mainType);
        },
        copyshow: function(obj) {
            // window.parent.cmedit.ManuscriptSystem.copyshow(obj);
            var _con = $(obj).siblings(".dropdown-menu");
            $("body").off("click").on("click", function(e) {
                if (!_con.is(event.target) && !$(obj).children().is(event.target) && (_con.has(event.target).length === 0) || _con.find('button').is(event.target)) {
                    $(".moreDropDown").removeClass("showDropDown");
                    _con.removeClass("showDropDown");
                } else {
                    if (_con.is(":hidden")) {
                        $(".showDropDown").removeClass("showDropDown");
                        _con.addClass("showDropDown");
                    };
                }
            });
            return false;
        },

        /**
         * 下载稿件选择
         * @returns {Boolean}
         */
        selectDownload: function() {
            var choosenList = $('#manusendtaskTable').bootstrapTable('getSelections');
            if (choosenList.length == 0) {
                $.notify("请先选择记录！");
                $('.manuLoader').hide();
                return false;
            } else {
                var mainGuids = [];
                var columnIds = [];
                var mainType = "";
                var params = {};
                for (var i = 0; i < choosenList.length; i++) {
                    mainGuids.push(choosenList[i].mainGuid);
                    columnIds.push(choosenList[i].mainColumnId);
                    mainType = choosenList[i].mainType;
                }
                params["mainGuids"] = mainGuids;
                params["columnIds"] = columnIds;
                params["mainType"] = mainType;
                window.parent.cmedit.ManuscriptSystem.showDownloadModal(params, "manuSendTask");
            }
        },
        /**
         * 实际签发操作
         * @param columnIds
         */
        distributeTarget: function(targetIds) {
            var postData;
            var mainGuids = [];
            //判断是单条记录选择还是勾选的
            if (topUtil.isNotEmpty(singleMainGuid)) {
                mainGuids.push(singleMainGuid);
                postData = {
                    targetIds: JSON.stringify(targetIds),
                    mainGuids: JSON.stringify(mainGuids),
                }
                singleMainGuid = '';
            } else {
                var choosenList = $('#manusendtaskTable').bootstrapTable('getSelections');
                var selectIds = [];
                for (var i = 0; i < choosenList.length; i++) {
                    selectIds.push(choosenList[i].mainGuid);
                }
                postData = {
                    targetIds: JSON.stringify(targetIds),
                    mainGuids: JSON.stringify(selectIds),
                }
            }
            topUtil.ajaxRequest({
                type: "post",
                async: true,
                dataType: "json",
                url: cmedit.global.cmsPath + "CmsNewTargetController/batchDistribute",
                data: postData,
                success: function(data) {
                    if (data.status) {
                        $.notify("签发稿件成功");
                        thisContext.initData();
                    } else {
                        $.notify(data.msg);
                    }
                }
            });
        }
    };
    return new TargetManagerClass();
})(jQuery, window, document);

$(cmedit.TargetManager.init());